import axios from "axios"
import { useUserStore } from "../../store/user.js"

const baseURL = import.meta.env.VITE_BASE_URL

const service = axios.create({
    baseURL: baseURL,
    timeout: 5000,
})

let userStore = useUserStore()
// 请求前的统一处理
service.interceptors.request.use(
    (config) => {
        config.headers.token = userStore.token
        return config
    },
    (error) => {
        console.error("request异常:", error)
        return Promise.reject(error)
    },
)

service.interceptors.response.use((response) => {
    const res = response.data
    if(response.status !== 200){
        return Promise.reject(res)
    }
    
    // 未登录
    if(res.code === 401){
        console.error("未登录/token错误")
    }
    
    // 权限不足
    if(res.code === 403){
        console.error("权限不足")
        // 提醒用户
    }
    
    return res
}, (error) => {
    console.error("响应异常", error)
})

export default service
